<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>AI 对话助手</h2>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div v-if="chatStore.messages.length === 0" class="empty-state">
        <a-empty description="开始你的对话吧" />
      </div>

      <div
        v-for="message in chatStore.messages"
        :key="message.id"
        class="message-wrapper"
        :class="message.type"
      >
        <div class="message-content">
          <div class="message-avatar">
            <a-avatar :style="{ backgroundColor: message.type === 'user' ? '#1890ff' : '#52c41a' }">
              {{ message.type === 'user' ? '你' : 'AI' }}
            </a-avatar>
          </div>
          <div class="message-bubble">
            <div 
              class="message-text" 
              :class="{ 'markdown-content': message.type === 'ai' }"
              v-html="formatMessage(message.content, message.type)"
            ></div>
            <div v-if="message.isStreaming" class="typing-indicator">
              <span></span><span></span><span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input-container">
      <a-input
        v-model:value="inputMessage"
        placeholder="输入你的消息..."
        size="large"
        :disabled="chatStore.isLoading"
        @press-enter="handleSend"
        class="chat-input"
      >
        <template #suffix>
          <a-button
            type="primary"
            :loading="chatStore.isLoading"
            :disabled="!inputMessage.trim()"
            @click="handleSend"
          >
            发送
          </a-button>
        </template>
      </a-input>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onMounted } from 'vue'
import { useChatStore } from '../stores/chat'
import { message as antMessage } from 'ant-design-vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css'

// 配置 marked
marked.setOptions({
  highlight: function(code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, { language: lang }).value
      } catch (err) {
        console.warn('Highlight error:', err)
      }
    }
    return hljs.highlightAuto(code).value
  },
  breaks: true, // 支持换行
  gfm: true, // 支持GitHub风格的Markdown
})

const chatStore = useChatStore()
const inputMessage = ref('')
const messagesContainer = ref(null)

// 格式化消息内容
const formatMessage = (text, messageType) => {
  if (!text) return ''
  
  // AI消息使用Markdown渲染
  if (messageType === 'ai') {
    try {
      return marked.parse(text)
    } catch (error) {
      console.error('Markdown parsing error:', error)
      // 如果Markdown解析失败，回退到普通文本
      return escapeHtml(text).replace(/\n/g, '<br>')
    }
  }
  
  // 用户消息保持原样，只做基本的HTML转义和换行处理
  return escapeHtml(text).replace(/\n/g, '<br>')
}

// HTML转义函数
const escapeHtml = (text) => {
  const div = document.createElement('div')
  div.textContent = text
  return div.innerHTML
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 监听消息变化，自动滚动
watch(() => chatStore.messages, () => {
  scrollToBottom()
}, { deep: true })

// 监听loading状态，确保完成后输入框为空
watch(() => chatStore.isLoading, (newVal, oldVal) => {
  // 当loading从true变为false时，确保输入框为空
  if (oldVal && !newVal) {
    nextTick(() => {
      inputMessage.value = ''
    })
  }
})

// 处理 SSE 流
const handleSSE = async (memoryId, userMessage) => {
  chatStore.setLoading(true)
  chatStore.addUserMessage(userMessage)

  // 创建空的AI消息，标记为流式传输中
  let fullContent = ''
  chatStore.setAiMessage('', true)

  try {
    const response = await fetch(`/ai/chat?memoryId=${memoryId}&message=${encodeURIComponent(userMessage)}`, {
      method: 'GET',
      headers: {
        'Accept': 'text/event-stream',
        'Cache-Control': 'no-cache',
      }
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    if (!response.body) {
      throw new Error('Response body is null')
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let buffer = ''

    try {
      while (true) {
        const { done, value } = await reader.read()

        if (done) {
          // 流结束，处理剩余的缓冲区数据
          if (buffer.trim()) {
            const lines = buffer.split('\n')
            for (const line of lines) {
              if (line.startsWith('data:')) {
                const chunk = line.substring(5)
                fullContent += chunk
              }
            }
            // 更新最后的数据
            if (fullContent) {
              chatStore.setAiMessage(fullContent, true)
            }
          }
          break
        }

        // 解码数据
        buffer += decoder.decode(value, { stream: true })

        // 处理完整的行
        let newlineIndex
        while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
          const line = buffer.substring(0, newlineIndex)
          buffer = buffer.substring(newlineIndex + 1)

          // 处理SSE格式
          if (line.startsWith('data:')) {
            // 提取数据内容（去掉"data: "前缀）
            const chunk = line.substring(5)
            fullContent += chunk
            // 实时更新UI，实现打字机效果
            chatStore.setAiMessage(fullContent, true)
            scrollToBottom()
          }
          // 忽略其他SSE字段（event:, id:, retry:等）
          // 空行表示事件结束，继续处理下一个事件
        }
      }
    } finally {
      // 确保流被正确关闭
      try {
        reader.releaseLock()
      } catch (e) {
        console.warn('Failed to release reader lock:', e)
      }
    }

    // 流结束，标记为完成
    chatStore.setAiMessage(fullContent, false)
    chatStore.setLoading(false)

    if (!fullContent.trim()) {
      console.warn('Received empty content from SSE stream')
      antMessage.warning('可能未接收到完整数据，请重试')
    }
    
    // 确保输入框在完成后为空
    await nextTick()
    inputMessage.value = ''

  } catch (error) {
    console.error('SSE Error:', error)
    // 如果有部分内容，保留它
    if (fullContent.trim()) {
      chatStore.setAiMessage(fullContent, false)
      antMessage.warning('连接中断，已保存部分内容')
    } else {
      chatStore.setAiMessage('抱歉，发生了错误：' + error.message, false)
      antMessage.error('发送消息失败，请重试')
    }
    chatStore.setLoading(false)
    
    // 确保输入框在出错后也为空
    await nextTick()
    inputMessage.value = ''
  }
}


// 发送消息
const handleSend = async () => {
  const userMessage = inputMessage.value.trim()
  if (!userMessage || chatStore.isLoading) {
    return
  }

  // 立即清空输入框
  inputMessage.value = ''
  
  // 等待下一个 tick 确保清空生效
  await nextTick()

  // 发送消息
  await handleSSE(chatStore.memoryId, userMessage)
  
  // SSE 完成后再次确保输入框为空
  await nextTick()
  inputMessage.value = ''
}

onMounted(() => {
  scrollToBottom()
})
</script>

<style scoped>
.chat-container {
  width: 100%;
  max-width: 900px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: white;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: white;
}

.chat-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #262626;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: #fafafa;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.message-wrapper {
  margin-bottom: 24px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-content {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.message-wrapper.user .message-content {
  flex-direction: row-reverse;
  margin-left: auto;
}

.message-wrapper.ai .message-content {
  flex-direction: row;
}

.message-avatar {
  flex-shrink: 0;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 12px;
  word-wrap: break-word;
  line-height: 1.6;
}

.message-wrapper.user .message-bubble {
  background: #1890ff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-wrapper.ai .message-bubble {
  background: white;
  color: #262626;
  border: 1px solid #e8e8e8;
  border-bottom-left-radius: 4px;
}

.message-text {
  white-space: pre-wrap;
}

/* Markdown 样式 */
.markdown-content {
  line-height: 1.6;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3),
.markdown-content :deep(h4),
.markdown-content :deep(h5),
.markdown-content :deep(h6) {
  margin-top: 16px;
  margin-bottom: 8px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-content :deep(h1) {
  font-size: 1.5em;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 8px;
}

.markdown-content :deep(h2) {
  font-size: 1.3em;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 6px;
}

.markdown-content :deep(h3) {
  font-size: 1.1em;
}

.markdown-content :deep(p) {
  margin: 8px 0;
}

.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  margin: 8px 0;
  padding-left: 24px;
}

.markdown-content :deep(li) {
  margin: 4px 0;
}

.markdown-content :deep(blockquote) {
  margin: 8px 0;
  padding: 8px 16px;
  border-left: 4px solid #1890ff;
  background-color: #f5f5f5;
  color: #666;
}

.markdown-content :deep(code) {
  padding: 2px 6px;
  background-color: #f5f5f5;
  border-radius: 3px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 0.9em;
}

.markdown-content :deep(pre) {
  margin: 12px 0;
  padding: 12px;
  background-color: #1e1e1e;
  border-radius: 6px;
  overflow-x: auto;
}

.markdown-content :deep(pre code) {
  padding: 0;
  background-color: transparent;
  color: #d4d4d4;
  font-size: 0.9em;
  line-height: 1.5;
}

.markdown-content :deep(table) {
  width: 100%;
  margin: 12px 0;
  border-collapse: collapse;
  border: 1px solid #e8e8e8;
}

.markdown-content :deep(th),
.markdown-content :deep(td) {
  padding: 8px 12px;
  border: 1px solid #e8e8e8;
  text-align: left;
}

.markdown-content :deep(th) {
  background-color: #fafafa;
  font-weight: 600;
}

.markdown-content :deep(tr:nth-child(even)) {
  background-color: #fafafa;
}

.markdown-content :deep(a) {
  color: #1890ff;
  text-decoration: none;
}

.markdown-content :deep(a:hover) {
  text-decoration: underline;
}

.markdown-content :deep(hr) {
  margin: 16px 0;
  border: none;
  border-top: 1px solid #e8e8e8;
}

.markdown-content :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 8px 0;
}

.typing-indicator {
  display: inline-flex;
  gap: 4px;
  margin-top: 8px;
  align-items: center;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #bfbfbf;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input-container {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  background: white;
}

.chat-input {
  display: flex;
  align-items: center;
}

.chat-input :deep(.ant-input) {
  padding-right: 100px;
}

.chat-input :deep(.ant-input-suffix) {
  position: absolute;
  right: 8px;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #d9d9d9;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #bfbfbf;
}
</style>

